package database;

//package au.com.bytecode.opencsv;

/**
Copyright 2005 Bytecode Pty Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A very simple CSV parser released under a commercial-friendly license.
 * This just implements splitting a single line into fields.
 *
 * @author Glen Smith
 * @author Rainer Pruy
 * @author Tristan Daniel Boucher (Formatting)
 * 
 * @version Commit #24
 */
public class CSVParser 
{
  /**
   * The default separator to use if none is supplied to the constructor.
   */
  public static final char DEFAULT_SEPARATOR = ',';

  /**
   * The initial size of the chunk of data that will be read in at one time.
   */
  public static final int INITIAL_READ_SIZE = 128;

  /**
   * The default quote character to use if none is supplied to the
   * constructor.
   */
  public static final char DEFAULT_QUOTE_CHARACTER = '"';


  /**
   * The default escape character to use if none is supplied to the
   * constructor.
   */
  public static final char DEFAULT_ESCAPE_CHARACTER = '\\';

  /**
   * The default strict quote behavior to use if none is supplied to the
   * constructor.
   */
  public static final boolean DEFAULT_STRICT_QUOTES = false;

  /**
   * The default leading whitespace behavior to use if none is supplied to the
   * constructor.
   */
  public static final boolean DEFAULT_IGNORE_LEADING_WHITESPACE = true;

  /**
   * This is the "null" character - if a value is set to this then it is ignored.
   * I.E. if the quote character is set to null then there is no quote character.
   */
  public static final char NULL_CHARACTER = '\0';

  /**
   * The character that is used as a separator between elements.
   */
  private final char my_separator;

  /**
   * The character used for quoted elements.
   */
  private final char my_quotechar;

  /**
   * The escape character \.
   */
  private final char my_escape;

  /**
   * Is strict quotes on?
   */
  private final boolean my_strict_quotes;

  /**
   * The pending line to be parsed.
   */
  private String my_pending;

  /**
   * Escape character in field?
   */
  private boolean my_in_field = false;

  /**
   * Flag to ignore leading white space in lines that are picked up by the reader.
   */
  private final boolean my_ignore_leading_white_space;


  /**
   * Constructs CSVParser using a comma for the separator.
   */
  public CSVParser() 
  {
    this(DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER);
  }

  /**
   * Constructs CSVParser with supplied separator.
   *
   * @param the_separator the delimiter to use for separating entries.
   */
  public CSVParser(final char the_separator) 
  {
    this(the_separator, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER);
  }


  /**
   * Constructs CSVParser with supplied separator and quote char.
   *
   * @param the_separator the delimiter to use for separating entries
   * @param the_quotechar the character to use for quoted elements
   */
  public CSVParser(final char the_separator, final char the_quotechar) 
  {
    this(the_separator, the_quotechar, DEFAULT_ESCAPE_CHARACTER);
  }

  /**
   * Constructs CSVReader with supplied separator and quote char.
   *
   * @param the_separator the delimiter to use for separating entries
   * @param the_quotechar the character to use for quoted elements
   * @param the_escape    the character to use for escaping a separator or quote
   */
  public CSVParser(final char the_separator, final char the_quotechar, 
                   final char the_escape) 
  {
    this(the_separator, the_quotechar, the_escape, DEFAULT_STRICT_QUOTES);
  }

  /**
   * Constructs CSVReader with supplied separator and quote char.
   * Allows setting the "strict quotes" flag
   *
   * @param the_separator    the delimiter to use for separating entries
   * @param the_quotechar    the character to use for quoted elements
   * @param the_escape       the character to use for escaping a separator or quote
   * @param the_strict_quotes if true, characters outside the quotes are ignored
   */
  public CSVParser(final char the_separator, final char the_quotechar, 
                   final char the_escape, final boolean the_strict_quotes) 
  {
    this(the_separator, the_quotechar, the_escape, 
         the_strict_quotes, DEFAULT_IGNORE_LEADING_WHITESPACE);
  }

  /**
   * Constructs CSVReader with supplied separator and quote char.
   * Allows setting the "strict quotes" and "ignore leading whitespace" flags
   *
   * @param the_separator               the delimiter to use for separating entries
   * @param the_quotechar               the character to use for quoted elements
   * @param the_escape                  the character to use for escaping a separator or quote
   * @param the_strict_quotes            if true, characters outside the quotes are ignored
   * @param the_ignore_leading_white_space if true, white space in front of a quote in a 
   * field is ignored
   */
  public CSVParser(final char the_separator, final char the_quotechar, 
                   final char the_escape, final boolean the_strict_quotes, 
                   final boolean the_ignore_leading_white_space) 
  {
    if (anyCharactersAreTheSame(the_separator, the_quotechar, the_escape)) 
    {
      throw new UnsupportedOperationException("The separator, quote, and " +
          "escape characters must be different!");
    }
    if (the_separator == NULL_CHARACTER) 
    {
      throw new UnsupportedOperationException("The separator character must be defined!");
    }
    this.my_separator = the_separator;
    this.my_quotechar = the_quotechar;
    this.my_escape = the_escape;
    this.my_strict_quotes = the_strict_quotes;
    this.my_ignore_leading_white_space = the_ignore_leading_white_space;
  }

  private boolean anyCharactersAreTheSame(final char the_separator, 
                                          final char the_quotechar, 
                                          final char the_escape) 
  {
    return isSameCharacter(the_separator, the_quotechar) || 
        isSameCharacter(the_separator, the_escape) || 
        isSameCharacter(the_quotechar, the_escape);
  }

  private boolean isSameCharacter(final char the_c1, final char the_c2) 
  {
    return the_c1 != NULL_CHARACTER && the_c1 == the_c2;
  }

  /**
   * @return true if something was left over from last call(s)
   */
  public boolean isPending() 
  {
    return my_pending != null;
  }

  public String[] parseLineMulti(final String the_next_line) throws IOException 
  {
    return parseLine(the_next_line, true);
  }

  public String[] parseLine(final String the_next_line) throws IOException 
  {
    return parseLine(the_next_line, false);
  }

  /**
   * Parses an incoming String and returns an array of elements.
   *
   * @param the_next_line the string to parse
   * @param the_multi 
   * @return the comma-tokenized list of elements, or null if nextLine is null
   * @throws IOException if bad things happen during the read
   */
  private String[] parseLine(final String the_next_line, final boolean the_multi) 
    throws IOException 
  {

    String[] to_return = null;

    if (!the_multi && my_pending != null) 
    {
      my_pending = null;
    }

    if (the_next_line == null) 
    {
      if (my_pending != null) 
      {
        final String s = my_pending;
        my_pending = null;
        to_return = new String[]{s};
      } 
      return to_return;
    }

    final List<String> tokens_on_this_line = new ArrayList<String>();
    StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE);
    boolean in_quotes = false;
    if (my_pending != null) 
    {
      sb.append(my_pending);
      my_pending = null;
      in_quotes = true;
    }
    for (int i = 0; i < the_next_line.length(); i++) 
    {

      final char c = the_next_line.charAt(i);
      if (c == this.my_escape) 
      {
        if (isNextCharacterEscapable(the_next_line, in_quotes || my_in_field, i)) 
        {
          sb.append(the_next_line.charAt(i + 1));
          i++;
        }
      } 
      else if (c == my_quotechar) 
      {
        if (isNextCharacterEscapedQuote(the_next_line, in_quotes || my_in_field, i)) 
        {
          sb.append(the_next_line.charAt(i + 1));
          i++;
        } 
        else 
        {
          //inQuotes = !inQuotes;

          // the tricky case of an embedded quote in the middle: a,bc"d"ef,g
          if (!my_strict_quotes &&
              //not on the beginning of the line
              i > 2 && 
              //not at the beginning of an escape sequence
              the_next_line.charAt(i - 1) != my_separator && 
              the_next_line.length() > (i + 1) &&
              //not at the end of an escape sequence  
              the_next_line.charAt(i + 1) != my_separator && 
              my_ignore_leading_white_space && sb.length() > 0 && 
              isAllWhiteSpace(sb))
          {
            sb.setLength(0);  //discard white space leading up to quote 
          }
          else
          {
            sb.append(c);
            //continue;
          }

          in_quotes ^= in_quotes;
        }
        my_in_field ^= my_in_field;
      } 
      else if (c == my_separator && !in_quotes) 
      {
        tokens_on_this_line.add(sb.toString());
        sb.setLength(0); // start work on next token
        my_in_field = false;
      } 
      else 
      {
        if (!my_strict_quotes || in_quotes) 
        {
          sb.append(c);
          my_in_field = true;
        }
      }
    }
    // line is done - check status
    if (in_quotes) 
    {
      if (the_multi) 
      {
        // continuing a quoted section, re-append newline
        sb.append("\n");
        my_pending = sb.toString();
        sb = null; // this partial content is not to be added to field list yet
      } 
      else 
      {
        throw new IOException("Un-terminated quoted field at end of CSV line");
      }
    }
    if (sb != null) 
    {
      tokens_on_this_line.add(sb.toString());
    }
    return tokens_on_this_line.toArray(new String[tokens_on_this_line.size()]);

      }

  /**
   * precondition: the current character is a quote or an escape.
   *
   * @param the_next_line the current line
   * @param the_in_quotes true if the current context is quoted
   * @param the_i        current index in line
   * @return true if the following character is a quote
   */
  private boolean isNextCharacterEscapedQuote(final String the_next_line, 
                                              final boolean the_in_quotes, 
                                              final int the_i) 
  {
    return the_in_quotes && // we are in quotes, therefore there can be escaped quotes in here.
        the_next_line.length() > (the_i + 1) && // there is indeed another character to check.
        the_next_line.charAt(the_i + 1) == my_quotechar;
  }

  /**
   * precondition: the current character is an escape.
   *
   * @param the_next_line the current line
   * @param the_in_quotes true if the current context is quoted
   * @param the_i        current index in line
   * @return true if the following character is a quote
   */
  protected boolean isNextCharacterEscapable(final String the_next_line, 
                                             final boolean the_in_quotes, 
                                             final int the_i) 
  {
    return the_in_quotes && // we are in quotes, therefore there can be escaped quotes in here.
        the_next_line.length() > (the_i + 1) && // there is indeed another character to check.
        (the_next_line.charAt(the_i + 1) == my_quotechar || 
        the_next_line.charAt(the_i + 1) == this.my_escape);
  }

  /**
   * precondition: sb.length() > 0.
   *
   * @param the_sb A sequence of characters to examine
   * @return true if every character in the sequence is whitespace
   */
  protected boolean isAllWhiteSpace(final CharSequence the_sb) 
  {
    boolean result = true;
    for (int i = 0; i < the_sb.length(); i++) 
    {
      if (!Character.isWhitespace(the_sb.charAt(i))) 
      {
        result = false;
      }
    }
    return result;
  }
}
//End of Class CSVParser